<template>
  <div class="app-container">
    <el-card class="operate-container box-card" shadow="hover">
      <i class="el-icon-tickets" style="margin-top: 5px"></i>
      <span style="margin-top: 5px">规格属性列表</span>
      <el-button
        type="primary"
        class="btn-add"
        icon="el-icon-plus"
        @click="handleAddSpec"
        size="mini"
      >
        添加规格
      </el-button>
      <el-button
        type="danger"
        class="btn-add"
        icon="el-icon-delete"
        @click="handleDelAll"
        size="mini"
      >
        批量删除
      </el-button>
      <div class="table-container">
        <el-table
          ref="productAttrTable"
          :data="list"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          v-loading="listLoading"
        >
          <el-table-column
            type="selection"
            width="60"
            align="center"
          ></el-table-column>
          <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
          <el-table-column label="规格名称" align="center">
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column label="可选值列表" align="center">
            <template slot-scope="scope">{{ scope.row.inputList }}</template>
          </el-table-column>
          <el-table-column label="排序" align="center" prop="sort" width="100"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                plain
                @click="handleUpdate(scope.$index, scope.row)"
                >编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                plain
                @click="handleDelete(scope.$index, scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.pageNum"
        :limit.sync="listQuery.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加属性弹框 -->
    <el-dialog :title="attrTitle" :visible.sync="dialogFormVisible">
      <el-form
        ref="attrForm"
        :model="attrForm"
        :rules="rules"
        label-width="140px"
      >
        <el-form-item label="规格名称：" prop="name">
          <el-input v-model="attrForm.name"></el-input>
        </el-form-item>
        <el-form-item label="规格值：" prop="dynamicTags">
          <el-tag
            :key="tag"
            v-for="tag in attrForm.dynamicTags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput"
            >+ 属性值</el-button
          >
        </el-form-item>
        <el-form-item label="商品类别排序" prop="sort">
          <el-input-number
            v-model="attrForm.sort"
            controls-position="right"
            :min="1"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { queryGoodsAttr,addGoodsAttr,updateGoodsAttr,delGoodsAttr } from "@/api/goods/goods";

export default {
  name: "spec",
  data() {
    return {
      listLoading: false,
      list: [
        {
          id: 1,
          name: '服务地区',
          inputList: '浙江,上海,北京,深圳,广东,云南,江苏,其他地区'
        },
        {
          id: 1,
          name: '企业人数',
          inputList: '0-20人,21-40人,41-60人,61-80人,81人以上'
        }
      ],

      // 分页参数
      total: 0,
      listQuery: {
        pageNum: 1,
        pageSize: 10
      },

      // 批量选择
      ids: [],

      // 属性弹框
      attrTitle: "",
      dialogFormVisible: false,
      attrForm: {
        dynamicTags: [],
      },
      rules: {
        name: [{ required: true, message: "请输入属性名称", trigger: "blur" }],
        dynamicTags: [{ required: true, message: "属性值不能为空", trigger: "blur" }],
        inputType: [{ required: true,message: "请选择规格值的录入方式", trigger: "blur" }],
        sort: [{ required: true,message: "请输入排序",trigger: "blur" }]
      },

      // 商品类别下拉选择框
      // CateOptions: [],

      inputVisible: false,
      inputValue: ""
    };
  },
  filters: {
    inputTypeFilter(value) {
      if (value == 1) {
        return '从列表中选取';
      } else {
        return '手工录入'
      }
    },
  },
  created() {
    this.getList();
    // this.getCateList();
  },
  methods: {
    // 获取相关的规格属性列表
    getList() {
      this.listLoading = true;
      queryGoodsAttr(this.listQuery).then(res => {
        this.listLoading = false;
        if(res.code == 200){
          this.list = res.rows;
          this.total = res.total;
        }else{
          return this.msgError('查询规格属性数据失败')
        }
      });
    },

    // 获取属性类别数据
    // getCateList() {
      // queryTypeList({
      //   pageNum: 1,
      //   pageSize: 1000
      // }).then(res => {
      //   // console.log(res)
      //   if(res.code == 200){
      //     this.CateOptions = res.rows;
      //     // console.log(this.CateOptions);
      //   }else {
      //     return this.msgError('获取属性类别数据失败！')
      //   }
      // });
    // },

    // 点击添加相关属性
    handleAddSpec() {
      this.dialogFormVisible = true;
      this.attrTitle = "添加规格属性";
      this.attrForm = {
        dynamicTags: []
      };
      // 默认选中点击来时的商品类别
      // this.attrForm.goodsAttributeCategoryId = Number(this.specId);
    },

    // 点击编辑相关属性
    handleUpdate(index, row) {
      this.dialogFormVisible = true;
      this.attrTitle = "编辑规格属性";
      this.attrForm = row;
      this.attrForm.dynamicTags = row.inputList.split(',')
    },

    // 点击提交属性
    submitForm() {
      this.$refs["attrForm"].validate(valid => {
        if (valid) {
          this.attrForm.inputList = this.attrForm.dynamicTags.join(',');
          this.attrForm.inputType = 0;
          this.attrForm.handAddStatus = 1;
          console.log(this.attrForm)
          if (this.attrForm.id !== undefined) {
            updateGoodsAttr(this.attrForm).then(res => {
              // console.log(res);
              if (res.code === 200) {
                this.msgSuccess("修改成功");
                this.dialogFormVisible = false;
                this.getList();
              } else {
                this.msgError(res.msg);
              }
            });
          } else {
            addGoodsAttr(this.attrForm).then(res => {
              // console.log(res)
              if (res.code === 200) {
                this.msgSuccess("新增成功");
                this.dialogFormVisible = false;
                this.getList();
              } else {
                this.msgError(res.msg);
              }
            });
          }
        }
      });
    },

    // 点击取消
    cancel(){
      this.dialogFormVisible = false;
      this.attrForm = {
        dynamicTags: []
      }
      this.getList();
    },

    // 移除属性值
    handleClose(tag) {
      this.attrForm.dynamicTags.splice(this.attrForm.dynamicTags.indexOf(tag), 1);
      this.$forceUpdate();
    },

    // 输入属性值
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // 添加属性值
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.attrForm.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },


    // 多选框选择
    handleSelectionChange(val) {
      this.ids = val.map(item => item.id);
    },
    // 点击批量删除按钮
    handleDelAll() {
      if (this.ids.length == 0) {
        return this.msgError("必须选择一项进行操作！");
      } else {
        var str = this.ids.join(",");
      }
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteData(str);
          this.ids = [];
        })
        .catch(() => {});
    },
    // 点击删除按钮
    handleDelete(index, row) {
      this.$confirm('确定要删除吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.deleteData(row.id)
      }).catch(() => {})
    },
    // 实现删除规格属性
    deleteData(id){
      delGoodsAttr(id).then(res => {
        if(res.code == 200){
          this.msgSuccess('删除成功')
          this.getList();
        }else {
          this.msgError('删除失败')
        }
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.table-container {
  margin-top: 20px;
}
.batch-operate-container {
  margin-top: 15px;
}
.btn-add {
  margin-left: 20px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
